package com.mzy.linear_struct.hot100.回溯;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: mizy3
 * @Date: 2024/08/27/下午10:41
 * @Description:
 */
public class Pro22括号生成 {
    public List<String> generateParenthesis(int n) {
        List<String> ans = new ArrayList<>();
        if (n == 0) {
            return ans;
        }

        StringBuilder builder = new StringBuilder();
        backtracking(n, builder, 0, 0, ans);
        return ans;
    }

    private void backtracking(int n, StringBuilder path, int open, int close, List<String> ans) {
        if (open < close || open > n) {
            return;
        }
        if (path.length() == n * 2) {
            ans.add(path.toString());
        }

        path.append("(");
        backtracking(n, path, open + 1, close, ans);
        path.deleteCharAt(path.length() - 1);
        path.append(")");
        backtracking(n, path, open, close + 1, ans);
        path.deleteCharAt(path.length() - 1);
    }

    public static void main(String[] args) {
        System.out.println(new Pro22括号生成().generateParenthesis(3));
    }
}




























